package com.mtz.service.impl;
import java.util.Date;

import com.mtz.dateobject.UserWechat;
import com.mtz.enums.ResultEnum;
import com.mtz.exception.MtzException;
import com.mtz.form.WechatForm;
import com.mtz.repository.UserWechatRepository;
import com.mtz.service.UserWechatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 煜赜
 * @date 2018/12/4 6:13
 */
@Service
@Slf4j
public class UserWechatServiceImpl implements UserWechatService {

    @Autowired
    private UserWechatRepository userWechatRepository;

    @Override
    public UserWechat findByOpenid(String openid) {
        UserWechat userWechat = userWechatRepository.findByOpenid(openid);
        if (userWechat == null) {
            throw new MtzException(ResultEnum.USER_NOT_EXIST);
        }
        return userWechat;
    }

    @Override
    public UserWechat findByUsername(String username) {
        UserWechat userWechat = userWechatRepository.findByUsername(username);
        if (userWechat == null) {
            throw new MtzException(ResultEnum.USER_NOT_EXIST);
        }
        return userWechat;
    }

    @Override
    public List<UserWechat> findByType(Integer type) {
        List<UserWechat> userWechatList = userWechatRepository.findByType(type);
        if (userWechatList.size() == 0) {
            throw new MtzException(ResultEnum.TYPE_NOT_EXIST);
        }
        return null;
    }

    @Override
    public void addUser(WechatForm wechatForm) {
        UserWechat userWechat = new UserWechat();
        userWechat.setOpenid(wechatForm.getOpenid());
        userWechat.setSessionKey(wechatForm.getSessionKey());
        userWechat.setNickname(wechatForm.getNickname());
        userWechat.setGender(wechatForm.getGender());
        userWechat.setAddress(wechatForm.getAddress());

        userWechatRepository.save(userWechat);
    }

    @Override
    public void setLocation(String openid, String longitude, String latitude) {
        UserWechat userWechat = userWechatRepository.findByOpenid(openid);
        userWechat.setLongitude(longitude);
        userWechat.setLatitude(latitude);
        userWechatRepository.save(userWechat);
    }
}
